/**
 * 文件下载与本地持久化相关工具
 */
import { isCloudReady, downloadCloudFile } from './cloud'

/**
 * 下载云文件到本地并以指定文件名保存
 */
export async function downloadAndSaveCloudFile(fileID: string, fileName: string): Promise<string> {
  if (!isCloudReady()) throw new Error('cloud not initialized')
  const temp = await downloadCloudFile(fileID)
  const fs = wx.getFileSystemManager()
  const base = `${wx.env.USER_DATA_PATH}/pdf_helper`
  try { fs.accessSync(base) } catch (_) { try { fs.mkdirSync(base, true) } catch (_) {} }
  const target = `${base}/${fileName || ('file-' + Date.now() + '.pdf')}`
  await new Promise<void>((resolve, reject) => {
    fs.saveFile({ tempFilePath: temp, filePath: target, success: () => resolve(), fail: (e) => reject(e) })
  })
  return target
}

export type DownloadRecord = { name: string; size: string | number; time: number; fileID: string; savedPath?: string }

/**
 * 新增一条下载记录并持久化
 */
export function addDownloadRecord(rec: DownloadRecord): void {
  const list: DownloadRecord[] = uni.getStorageSync('downloads') || []
  list.unshift(rec)
  uni.setStorageSync('downloads', list)
}

/**
 * 获取下载记录列表
 */
export function listDownloadRecords(): DownloadRecord[] {
  return uni.getStorageSync('downloads') || []
}

